 package com.ican.nc;

import java.net.URL;

import javax.annotation.Resource;

import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.ican.common.SystemConstants;
import com.ican.domain.product.Product;
import com.ican.service.product.ProductService;
import com.ican.service.rule.RuleConfigService;
import com.ican.util.MD5Util;

@Service("ruleCategoryScan")
public class RuleCategoryScan {
    private final static Logger logger = LoggerFactory.getLogger(RuleCategoryScan.class);
    
    private ProductService productService;
    private RuleConfigService ruleConfigService;
    
    public void scanCategory(ParseRuleVo rule, String url) {
        Object[] resultList = null;
        String result = null;
        TagNode tagNode = null;
        HtmlCleaner html = new HtmlCleaner();
        try {
            tagNode = html.clean(new URL(url));
            //解析所有详情页
            resultList = ParseUtil.evaluateXPath(tagNode, rule.getDpUrl().getXpath());
            if(resultList != null){
                for(Object o : resultList){
                    result = ParseUtil.tagNodeText(o);
                    if(result == null || result.length() < 1){
                        continue;
                    }
                    result = ParseUtil.parseResult(result, rule.getDpUrl());
                    Product product = new Product();
                    product.setCategoryId(rule.getProCateId());
                    product.setLangId(rule.getLangId());
                    product.setUrl(result);
                    product.setUrlFlag(MD5Util.Md5(result));
                    product.setRuleId(rule.getId());
                    productService.addProduct(product);
                }
            }
            //解析下一页
            result = ParseUtil.loadCommon(tagNode, rule.getNextPage());
            if(result != null && result.length() > 0 && !url.equals(result)){//有下一页
                this.scanCategory(rule, result);
            }else{//没有下一页
                ruleConfigService.updateCategoryScanStatus(rule.getRuleCateId(), SystemConstants.RULE_CONFIG_SCAN_STATUS_SUCCESS);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ruleConfigService.updateCategoryScanStatusAndLastPageUrl(rule.getRuleCateId(), SystemConstants.RULE_CONFIG_SCAN_STATUS_FAILED, url);
        }
    }
    
    @Resource
    public void setProductService(ProductService productService) {
        this.productService = productService;
    }
    @Resource
    public void setRuleConfigService(RuleConfigService ruleConfigService) {
        this.ruleConfigService = ruleConfigService;
    }
}
